import datetime

from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views.decorators.http import require_http_methods, require_POST, require_GET
from .forms import PubBlogForm, BlogCommentForm
from .models import Blog, BlogCategory, BlogComment


# Create your views here.

def index(request):
    blogs = Blog.objects.all()
    return render(request, 'index.html', context={'blogs': blogs})


def blog_detail(request, blog_id):
    try:
        blog = Blog.objects.get(pk=blog_id)
    except Blog.DoesNotExist:
        blog = None
    return render(request, 'blog_detail.html', context={'blog': blog})


@login_required
@require_http_methods(['GET', 'POST'])
def pub_blog(request):
    if request.method == 'GET':
        categories = BlogCategory.objects.all()
        return render(request, 'pub_blog.html', context={'categories': categories})
    else:
        pubform = PubBlogForm(request.POST)
        if pubform.is_valid():
            title = pubform.cleaned_data['title']
            content = pubform.cleaned_data['content']
            category = pubform.cleaned_data['category']
            blog = Blog.objects.create(
                title=title,
                content=content,
                category_id=category,
                author=request.user
            )
            return JsonResponse({'code': 200, 'message': '发布成功', 'data': {'blog_id': blog.id}})
        return JsonResponse({'code': 400, 'message': pubform.errors})


@login_required
@require_POST
def pub_comment(request):
    form = BlogCommentForm(request.POST)
    if form.is_valid():
        blog_id = form.cleaned_data['blog_id']
        content = form.cleaned_data['content']
        BlogComment.objects.create(content=content, blog_id=blog_id, author=request.user)
        return redirect(reverse('blog:blog_detail', kwargs={'blog_id': blog_id}))


@require_GET
def serch_blog(request):
    keyword = request.GET.get('search')
    blogs = Blog.objects.filter(Q(title__icontains=keyword) | Q(content__icontains=keyword)).all()
    return render(request, 'index.html', context={'blogs': blogs})
